<script setup lang="ts">
import { ref, watch } from "vue";
import type { RoleFormItemProps } from "../utils/types";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { message } from "@/utils/message";

const props = defineProps<RoleFormItemProps>();
const emit = defineEmits(["success"]);

const formRef = ref();
const form = ref<{
  deviceName?: string;
  roles?: Array<string>;
}>({});

// 表单规则
const rules = {
  roles: [
    {
      required: true,
      message: "请选择角色",
      trigger: "blur"
    }
  ]
};

// 角色列表
const roleOptions = ref([]);

watch(
  () => props.form,
  val => {
    form.value = { ...val };
  },
  {
    immediate: true
  }
);

// 加载角色数据
http
  .post(changeHttpLink("index.php/role/role/list"), {
    data: {}
  })
  .then((res: any) => {
    if (res.Success) {
      roleOptions.value = res.Data.Items;
    } else {
      message(res.Message, { type: "error" });
    }
  })
  .catch(err => {
    message(err.message, { type: "error" });
  });

function submitForm() {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      const params = { ...form.value };

      http
        .post(changeHttpLink("index.php/device/device/assign_role"), {
          data: params
        })
        .then((res: any) => {
          if (res.Success) {
            message("分配角色成功", { type: "success" });
            emit("success");
          } else {
            message(res.Message, { type: "error" });
          }
        })
        .catch(err => {
          message(err.message, { type: "error" });
        });
    }
  });
}
</script>

<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    label-width="100px"
    class="w-full"
  >
    <el-form-item label="设备名称">
      <el-input v-model="form.deviceName" disabled />
    </el-form-item>
    <el-form-item label="分配角色" prop="roles">
      <el-select v-model="form.roles" placeholder="请选择角色" multiple>
        <el-option
          v-for="item in roleOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm"> 确定 </el-button>
      <el-button @click="formRef.value.resetFields()"> 重置 </el-button>
    </el-form-item>
  </el-form>
</template>
